const Koa = require("koa");
const Router = require("koa-router");
const mockList = require("./mock");

const app = new Koa();
const router = new Router();

// 把ctx 传给fn ，可以拿到请求的url/method/等等
async function getRes(fn,ctx) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const res = fn(ctx);
      resolve(res);
    }, 1000);
  });
}

// 注册 mock 路由
mockList.forEach((item) => {
  const { url, method, response } = item;
  router[method](url, async (ctx) => {
    const res = await getRes(response,ctx);   // 模拟一个异步网络请求时间
    ctx.body = res; //输出结果
  }); 
});

app.use(router.routes());
app.listen(3001); //port 端口
